import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.DriverManager;
import java.sql.Statement;

public class Database {

	private static Database singleton;
	
    public static Database getInstance() {
    	if(singleton == null) {
    		singleton = new Database();
	    }
	  	return singleton;
	}

    private Connection db;
    
	protected Database() {
	    try {
	        // Load the JDBC driver
	        String driverName = "org.sqlite.JDBC"; // MySQL MM JDBC driver
	        Class.forName(driverName);
	    
	        // Create a connection to the database
	        String url = "jdbc:sqlite:///C:\\shogun.db"; // a JDBC url
	        db = DriverManager.getConnection(url);
	        System.out.println("Database Connection Started");
	    } catch (ClassNotFoundException e) {
	        // Could not find the database driver
	    	System.out.println("Failed to find driver.");
	    } catch (SQLException e) {
	        // Could not connect to the database
	    	System.out.println("Error: " + e.getMessage());
	    }
	    
	    // Try creating database tables (in case this is the first time accessing the db)
	    try {
	        Statement s = db.createStatement();
	        s.execute("CREATE TABLE users (username text(50), password text(50))");
	        System.out.println("Database Created");
	    } catch (SQLException e) {
	    	System.out.println("Database Loaded");
	    }
	}

	public static void insert(String cmd) {
		Connection db = getInstance().db;
	    try {
	        Statement insertStatement = db.createStatement();
	        insertStatement.executeUpdate(cmd);
	    } catch (SQLException e) {
	    	System.out.println("Error: " + e.getMessage());
	    }
	}	
	
	public static ResultSet query(String cmd) {
		Connection db = getInstance().db;
	    try {
	        Statement queryStatement = db.createStatement();
	        return queryStatement.executeQuery(cmd);        
	    } catch (SQLException e) {
	    	System.out.println("Error: " + e.getMessage());
	    }
		return null;
	}
}
